﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Windows.Controls;
using BaocaoNPC.common;
using Component;
using CMISLibrary;
using CMISLibrary.Libraries;
using System.IO;
using Microsoft.VisualBasic;
using BaocaoNPC.Usercontrols.reports;
using Ionic.Zip;
using bus_TienichNPC;

namespace BaocaoNPC.Usercontrols
{
    /// <summary>
    /// Interaction logic for ChamNoTheoFile_DienBien.xaml
    /// </summary>
    public partial class ChamNoTheoFile_DienBien : UserControl
    {
        #region Khai báo biến
        public String strMa_dviqly = NPCUS_DanhMuc.Pglobal.strMa_dviqly != "" && NPCUS_DanhMuc.Pglobal.strMa_dviqly != null ? NPCUS_DanhMuc.Pglobal.strMa_dviqly : "PA";
        public String strTenDNHap = NPCUS_DanhMuc.Pglobal.strTen_dangnhap != "" && NPCUS_DanhMuc.Pglobal.strTen_dangnhap != null ? NPCUS_DanhMuc.Pglobal.strTen_dangnhap : "PA";
        public String strTen_dviqly = NPCUS_DanhMuc.Pglobal.strTen_dviqly != "" && NPCUS_DanhMuc.Pglobal.strTen_dviqly != null ? NPCUS_DanhMuc.Pglobal.strTen_dviqly : "cty..";
        public String strTen_dviqly_CT = NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT != "" && NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT != null ? NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT : "cap tren";
        public String strMa_TNgan = NPCUS_DanhMuc.Pglobal.strTen_dangnhap != "" && NPCUS_DanhMuc.Pglobal.strTen_dangnhap != null ? NPCUS_DanhMuc.Pglobal.strTen_dangnhap.ToUpper() : "PA";
        string pfile = "";
        string maloi = "";
        DataTable dt_ReadFileExcel = new DataTable();
        DataSet ds_CN = new BCNPCEntities.EXCEL.ds_CN();
        DataSet ds_CAPNHAT = new BCNPCEntities.EXCEL.ds_CAPNHAT();
        //DataSet dsCNfile = new BCNPCEntities.EXCEL.dsCNFileExcel();
        cls_ImportExcel_bus cls = new cls_ImportExcel_bus();
        CN_THEODOINO_bus THEODOINO_bus = new CN_THEODOINO_bus();
        DataSet dsThuNganVien = new DataSet();
        string check_cham = "";
        int thang = 0, nam = 0;
        #endregion

        public ChamNoTheoFile_DienBien()
        {
            InitializeComponent();
            dtpNgayNOP.SelectedDate = DateTime.Now;
        }

        private void btnDuongdan_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog fld = new System.Windows.Forms.OpenFileDialog();
            fld.Title = "Chọn file cập nhật chấm nợ";
            fld.Filter = "Excel Files(*.xls)|*.xls";
            try
            {
                if (fld.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    txtDuongDan.Text = fld.FileName.ToString();
                }
                if (txtDuongDan.Text.Length > 0)
                {
                    string[] filenames = txtDuongDan.Text.Split('\\');
                    foreach (string sfilename in filenames)
                    {
                        if (sfilename.Contains(".xls"))
                            pfile = sfilename.Substring(0, sfilename.Length - 4);
                    }
                }
            }
            catch
            {
                //fld.SelectedPath = "My Computer";
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            BaocaoNPC.common.GlobalServices.Service_NPCUS.select_THANGNAMCONGNO(strMa_dviqly, ref thang, ref nam);
            lblthangnam.Content = "Tháng năm công nợ: " + thang.ToString() + "/" + nam.ToString();
            //dsThuNganVien = new DataSet();
            //dsThuNganVien = BaocaoNPC.common.GlobalServices.Service_NPCUS.select_ThuNganVien(strMa_dviqly);
            //if (dsThuNganVien != null) txtThuNganVien.AddItem(new CMIS2_TextBox.AutoCompleteEntry(dsThuNganVien));
            //txtThuNganVien.FocusAutoText();
        }

        private void UserControl_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void copy_dataTable(DataTable dtnguon, DataTable dtDich)
        {
            try
            {
                DataRow[] rgINS = dtnguon.Select();
                for (int i = 0; i < rgINS.Length; i++)
                {
                    DataRow dr = dtDich.NewRow();
                    dr["CHON"] = rgINS[i]["CHON"];
                    dr["DACHAM"] = rgINS[i]["DACHAM"];
                    dr["STT"] = rgINS[i]["STT"];
                    dr["KYTHANGNAM"] = rgINS[i]["KYTHANGNAM"];
                    dr["MA_DVIQLY"] = rgINS[i]["MA_DVIQLY"];
                    dr["MA_KHANG"] = rgINS[i]["MA_KHANG"];
                    dr["TEN_KHANG"] = rgINS[i]["TEN_KHANG"];
                    dr["TEN_TNGAN"] = rgINS[i]["TEN_TNGAN"];
                    dr["DCHI_KHANG"] = rgINS[i]["DCHI_KHANG"];
                    dr["MA_SOGCS"] = rgINS[i]["MA_SOGCS"];
                    dr["MA_TNGAN"] = rgINS[i]["MA_TNGAN"];
                    dr["TEN_TNGAN"] = rgINS[i]["TEN_TNGAN"];
                    dr["TONGTIEN"] = rgINS[i]["TONGTIEN"];
                    dr["TIEN_NO"] = rgINS[i]["TIEN_NO"];
                    dr["THUE_NO"] = rgINS[i]["THUE_NO"];
                    dr["SO_SERY"] = rgINS[i]["SO_SERY"];
                    dr["ID_HDON"] = rgINS[i]["ID_HDON"];
                    dr["SO_BBGIAO"] = rgINS[i]["SO_BBGIAO"];
                    dr["NGAY_GIAO"] = rgINS[i]["NGAY_GIAO"];
                    dr["TRANGTHAI"] = rgINS[i]["TRANGTHAI"];
                    dr["CHAM"] = rgINS[i]["CHAM"];
                    string a = dr["NGAY_CHAMNO"].ToString();
                    //if(dr["NGAY_CHAMNO"].ToString() != "")
                    //dr["NGAY_CHAMNO"] = DateTime.Parse(rgINS[i]["NGAY_CHAMNO"].ToString()).ToString("dd/MM/yyyy");
                    dr["NGAY_CHAMNO"] = rgINS[i]["NGAY_CHAMNO"];
                    dtDich.Rows.Add(dr);
                    dtDich.AcceptChanges();
                }
            }
            catch (Exception ex)
            { }
        }

        private void btnLaySoLieu_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.Cursor = Cursors.Wait;
                if (txtDuongDan.Text.Trim() == "")
                {
                    TootsNPC.ShowMessage.SetStatus("ERROR", this, btnLaySoLieu, "lblstatus", "Hãy chọn file excel");
                    ds_CN.Tables["dsCNFileExcel"].Rows.Clear();
                    dgrHDON_CNO.ItemsSource = null;
                    return;
                }
                dt_ReadFileExcel = new DataTable();
                dt_ReadFileExcel = TootsNPC.compression.dsReadExcel(txtDuongDan.Text, 0);
                if (dt_ReadFileExcel.Rows.Count == 0)
                {
                    TootsNPC.ShowMessage.SetStatus("ERROR", this, btnLaySoLieu, "lblstatus", "file không có số liệu!");
                    ds_CN.Tables["dsCNFileExcel"].Rows.Clear();
                    dgrHDON_CNO.ItemsSource = null;
                    return;
                }
                //DataTable dt = new DataTable();
                string ma_so = "";
                string[] ma_sgcs;
                ds_CN.Tables["dsCNFileExcel"].Rows.Clear();
                for (int j = 0; j < dt_ReadFileExcel.Rows.Count; j++)
                {
                    ma_sgcs = dt_ReadFileExcel.Rows[j][0].ToString().Split(':');
                    if (ma_sgcs[0] == "SGCS ")
                    {
                        ma_so = ma_sgcs[1].ToString();
                        for (int i = 0; i < dt_ReadFileExcel.Rows.Count; i++)
                        {
                            // lấy dòng check                    
                            if (dt_ReadFileExcel.Rows[i][0].ToString().Trim() != "")
                            {
                                check_cham = "CHECK";
                            }
                            else
                            { check_cham = "UNCHECK"; }
                            // tiếp tục kiểm tra dong mã khách hàng và id hóa đơn
                            if (dt_ReadFileExcel.Rows[i][1].ToString().Trim() != "")
                            {
                                if (TootsNPC.NPCNumber.numberic(dt_ReadFileExcel.Rows[i][1].ToString()))
                                {
                                    string ma_sogcs = ma_so;
                                    string stt = dt_ReadFileExcel.Rows[i][1].ToString();
                                    DataTable dtb = new DataTable();
                                    //dtb = THEODOINO_bus.SELECT_HDON_STT(strMa_dviqly.ToString(), ma_sgcs.ToString(), dt_ReadFileExcel.Rows[i][1].ToString());
                                    //DataSet ds = THEODOINO_bus.SELECT_HDON_STT(strMa_dviqly, ma_sogcs,check_cham, stt);
                                    DataSet ds = GlobalServices.Service_NPCUS.SELECT_HDON_STT(strMa_dviqly, ma_sogcs, check_cham, stt);
                                    DataTable data = ds.Tables[0].Copy();
                                    data.DefaultView.RowFilter = "MA_SOGCS = '" + ma_so +"'";
                                    if (ds != null)
                                    {
                                        if (ds.Tables[0].Rows.Count > 0)
                                            copy_dataTable(ds.Tables[0], ds_CN.Tables["dsCNFileExcel"]);
                                    }
                                }
                            }
                        }
                    }
                }                
                dgrHDON_CNO.ItemsSource = ds_CN.Tables["dsCNFileExcel"].DefaultView;
                if (ds_CN.Tables["dsCNFileExcel"].Rows.Count > 0)
                {
                    string thunganvien = ds_CN.Tables["dsCNFileExcel"].Rows[0]["MA_TNGAN"].ToString() + " --- " + ds_CN.Tables["dsCNFileExcel"].Rows[0]["TEN_TNGAN"].ToString();
                    txtThuNganVien.Text = thunganvien;
                    Decimal total = TootsNPC.NPCDatasetTable.SumColumnTable(ds_CN.Tables["dsCNFileExcel"], "TONGTIEN");
                    Decimal check = TootsNPC.NPCDatasetTable.SumCheckTable(ds_CN.Tables["dsCNFileExcel"], "TONGTIEN", "True");
                    //Decimal uncheck = TootsNPC.NPCDatasetTable.SumCheckTable(ds_CN.Tables["dsCNFileExcel"], "TONGTIEN", "False");

                    int countuncheck = TootsNPC.NPCDatasetTable.CountCheckTable(ds_CN.Tables["dsCNFileExcel"], "CHON", "False");
                    int countcheck = TootsNPC.NPCDatasetTable.CountCheckTable(ds_CN.Tables["dsCNFileExcel"], "CHON", "True");

                    lblThongtin.Content = "Hóa đơn chấm: " + countcheck.ToString() + " - Tổng tiền: " + check.ToString("#,###,###,###") +
                                          " - Tổng hóa đơn: " + ds_CN.Tables["dsCNFileExcel"].Rows.Count.ToString() + " - Tổng tiền: " + total.ToString("#,###,###,###");
                }
                this.Cursor = Cursors.Arrow;
            }
            catch (Exception ex)
            {
                TootsNPC.ShowMessage.SetStatus("ERROR", this, btnLaySoLieu, "lblstatus", ex.ToString());
            }
        }

        private void btnCapNhat_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int dem = 0;
                this.Cursor = Cursors.Wait;
                // check ngay
                if (dtpNgayNOP.Text == string.Empty)
                {
                    TootsNPC.ShowMessage.SetStatus("ERROR", this, btnCapNhat, "lblstatus", "Hãy chọn ngày cập nhật số liệu!");
                    return;
                }
                string ERRO = "";
                for (int j = 0; j < dgrHDON_CNO.Items.Count; j++)
                {
                    DataGridRow row = (DataGridRow)dgrHDON_CNO.ItemContainerGenerator.ContainerFromIndex(j);
                    CheckBox chk = dgrHDON_CNO.Columns[1].GetCellContent(row) as CheckBox;
                    if (chk.IsChecked == true)
                        dem++;
                }
                int pcount1 = ds_CN.Tables["dsCNFileExcel"].Rows.Count;
                if (dem == 0)
                { TootsNPC.ShowMessage.SetStatus("ERROR", this, btnCapNhat, "lblstatus", "Không có hóa đơn nào được chọn chấm lần này"); return; }
                if (pcount1 == 0)
                { TootsNPC.ShowMessage.SetStatus("ERROR", this, btnCapNhat, "lblstatus", "Không có dữ liệu chấm nợ"); return; }

                if (MessageBox.Show("Bạn có muốn thực hiện chấm nợ cho" + dem +" hóa đơn ?", "Thông báo", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
                {
                    // nhận số liệu vào off line
                    DataTable dt = ds_CN.Tables["dsCNFileExcel"] as DataTable;
                    for (int i = 0; i < dgrHDON_CNO.Items.Count; i++)
                    {
                        DataGridRow row = (DataGridRow)dgrHDON_CNO.ItemContainerGenerator.ContainerFromIndex(i);
                        CheckBox chk = dgrHDON_CNO.Columns[1].GetCellContent(row) as CheckBox;
                        if (chk.IsChecked == true)
                        {
                        if (dt.Rows[i]["DACHAM"].ToString() == "False")
                        {
                            ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE"].Rows.Clear();
                            DataRow dr = ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE"].NewRow();
                            //dr["ID_CAYLUOIDIEN"] = OMS_DANHMUC.Pglobal.strMa_dviqly;
                            dr["MA_DVIQLY"] = dt.Rows[i]["MA_DVIQLY"].ToString();
                            dr["MA_KHANG"] = dt.Rows[i]["MA_KHANG"].ToString();
                            dr["ID_HDON"] = Convert.ToInt64(dt.Rows[i]["ID_HDON"]);
                            dr["TIEN_NOP"] = Convert.ToDecimal(dt.Rows[i]["TIEN_NO"].ToString());
                            dr["THUE_NOP"] = Convert.ToDecimal(dt.Rows[i]["THUE_NO"].ToString());
                            dr["SO_BBGIAO"] = Convert.ToInt64(dt.Rows[i]["SO_BBGIAO"]);
                            dr["MA_TNGAN"] = dt.Rows[i]["MA_TNGAN"].ToString();
                            dr["MA_TNGAN_THUHO"] = dt.Rows[i]["MA_TNGAN"].ToString();
                            dr["NGAY_CHAMNO"] = dtpNgayNOP.SelectedDate.Value.Date;
                            dr["NAM_HT"] = nam;
                            dr["THANG_HT"] = thang;
                            dr["TRANGTHAI"] = 0;
                            dr["GROUP_NHOM"] = "";
                            dr["NGUOI_TAO"] = strTenDNHap;
                            dr["TINHTRANGIN"] = 0;
                            dr["NGAY_TAO"] = DateTime.Now;
                            ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE"].Rows.Add(dr);
                            ds_CAPNHAT.AcceptChanges();
                            //if (!cls.insert_NPC_CHAMNO_OFFLINE(ds_CAPNHAT, ref maloi))
                            if (!GlobalServices.Service_NPCUS.insert_NPC_CHAMNO_OFFLINE(ds_CAPNHAT, ref maloi))
                            {
                                TootsNPC.ShowMessage.SetStatus("ERORR", this, btnCapNhat, "lblstatus", maloi);
                                return;
                            }
                            //Ghilog
                            ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE_LOG"].Rows.Clear();
                            DataRow drlog = ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE_LOG"].NewRow();
                            drlog["MA_DVIQLY"] = dt.Rows[i]["MA_DVIQLY"].ToString();
                            drlog["MA_KHANG"] = dt.Rows[i]["MA_KHANG"].ToString();
                            drlog["ID_HDON"] = Convert.ToInt64(dt.Rows[i]["ID_HDON"]);
                            drlog["SO_BBGIAO"] = Convert.ToInt64(dt.Rows[i]["SO_BBGIAO"]);
                            drlog["NAM_HT"] = nam;
                            drlog["THANG_HT"] = thang;
                            drlog["MA_TNGAN"] = dt.Rows[i]["MA_TNGAN"].ToString();
                            drlog["NGAY_CHAMNO"] = dtpNgayNOP.SelectedDate.Value.Date;
                            drlog["TRANGTHAI"] = 3;
                            drlog["NGUOI_TAO"] = strTenDNHap;
                            drlog["NGAY_TAO"] = DateTime.Now;
                            drlog["GIO"] = DateTime.Now.Hour;
                            ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE_LOG"].Rows.Add(drlog);
                            ds_CAPNHAT.AcceptChanges();
                            if (!GlobalServices.Service_NPCUS.insert_NPC_CHAMNO_OFFLINE_LOG(ds_CAPNHAT, ref maloi))
                            //if (!cls.insert_NPC_CHAMNO_OFFLINE_LOG(ds_CAPNHAT, ref maloi))
                            {
                                TootsNPC.ShowMessage.SetStatus("ERORR", this, btnCapNhat, "lblstatus", maloi);
                                //chamno = false;
                            }
                        }
                    }
                    }
                    TootsNPC.ShowMessage.SetStatus("SUCCESS", this, btnCapNhat, "lblstatus", "Cập nhật số liệu thành công");
                }
                this.Cursor = Cursors.Arrow;
            }
            catch (Exception ex)
            {
                TootsNPC.ShowMessage.SetStatus("ERORR", this, btnCapNhat, "lblstatus", ex.ToString());
            }
        }

        private void CHECK_CHAM_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}
